<template>
  <div id="box">
    <img class="img1" src="http://chst.vip:8081/stu2/img/bg2.fc58c850.png" />
    <div id="form">
      <!-- 添加的图标 -->
      <div class="iconBox" @click="isErwei = !isErwei">
        <svg class="icon" aria-hidden="true">
          <use
            :xlink:href="
              isErwei ? '#icon-erweimajiaobiao' : '#icon-diannaojiaobiao'
            "
          ></use>
        </svg>
      </div>
      <!-- 标题 -->
      <h2 class="hh">后台管理系统</h2>
      <!-- 二维码登入 -->
      <div class="erwei" v-if="isErwei">
        <div class="imgBox">
          <img :src="erweiImg" class="img2" />
          <div class="mask" v-show="isScancode"></div>
        </div>
        <b>手机扫描二维码登入</b>
      </div>
      <!-- 普通登入输入框 -->
      <div class="input" v-else>
        <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <!-- 用户名输入框 -->
          <el-form-item label="用户名" prop="username">
            <el-input
              type="text"
              v-model="ruleForm.username"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <!-- 密码输入框 -->
          <el-form-item label="密码" prop="password">
            <el-input
              type="password"
              v-model="ruleForm.password"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <!-- 验证输入框 -->
          <el-form-item label="验证码" prop="verify">
            <div class="content">
              <el-input
                type="text"
                v-model="ruleForm.captcha"
                autocomplete="off"
                class="el-input-3"
                @keydown.native.13="submitForm('ruleForm')"
              >
              </el-input>
              <span class="span" v-html="captcha" @click="getcaptcha()"></span>
            </div>
          </el-form-item>
          <!-- 提交按钮 -->
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >提交</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
    <video
      src="../../assets/video/54aff53af2f93c5e8efaf382a5994dc8.mp4"
      autoplay
      loop
      muted
    ></video>
  </div>
</template>

<script>
//引入socket.io客户端
import io from "socket.io-client";
//引入qrcode，用于将二维码地址生成二维码的依赖
import qr from "qrcode";

import {
  loginApi,
  captchaApi,
  verifyApi,
  getCodeApi,
  erweiLoginApi,
} from "@/api";
import { mapMutations } from "vuex";
export default {
  mounted() {
    this.getcaptcha();
  },
  data() {
    //验证用户名框
    var validateName = (rule, value, callback) => {
      if (!/^[-_a-zA-Z0-9]{3,16}$/.test(value)) {
        callback(new Error("用户名（4到16位，字母数字下划线，减号）"));
      } else {
        if (this.ruleForm.password !== "") {
          this.$refs.ruleForm.validateField("password");
        }
        callback();
      }
    };
    //验证密码框
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("密码不能为空！"));
      } else {
        callback();
      }
    };
    //验证验证框
    var validateVerify = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("密码不能为空！"));
      } else {
        callback();
      }
    };
    return {
      captcha: "",
      isErwei: false,
      isScancode: false,
      erweiImg: "",
      ruleForm: {
        username: "",
        password: "",
        captcha: "",
      },

      //验证规则
      rules: {
        username: [{ validator: validateName, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
        captcha: [{ validator: validateVerify, trigger: "blur" }],
      },
    };
  },
  methods: {
    ...mapMutations(["SETUSERINFO"]),
    getcaptcha() {
      captchaApi().then((res) => {
        // console.log(res);
        this.captcha = res.data.img;
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          //校验验证码
          verifyApi(this.ruleForm.captcha).then((res) => {
            //验证通过
            // console.log(res);
            if (res.data.state) {
              //验证成功之后进行登入请求
              loginApi(this.ruleForm.username, this.ruleForm.password).then(
                (res) => {
                  // console.log(res);
                  //登入成功
                  if (res.data.state) {
                    localStorage.setItem("qf-token", res.data.token);
                    localStorage.setItem(
                      "qf-info",
                      JSON.stringify(res.data.userInfo)
                    );
                    this.SETUSERINFO(res.data.userInfo);
                    this.$router.push("/");
                    loading.close();
                  } else {
                    loading.close();
                    this.$message.error("用户名或者密码错误！");
                  }
                }
              );
            } else {
              this.getcaptcha();
              this.ruleForm.captcha = "";
              this.$message.error("输入的验证码错误！");
              loading.close();
            }
          });
        } else {
          //本地校验失败
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  watch: {
    isErwei(newval) {
      // console.log(newval);
      if (newval) {
        let socket = io("ws://chst.vip");
        //socket.on意思是接收什么事件，第一个参数为接收的事件，这里是接收成功的事件
        socket.on("connect", () => {
          // console.log('连接成功');
          //连接成功之后发送请求获取二维码地址
          getCodeApi().then((res) => {
            // console.log(res);
            let qrUrl = res.data.scanCodeUrl;
            //使用qr的toDataURL方法将二维码地址转成二维码
            qr.toDataURL(qrUrl, (err, imgUrl) => {
              if (err) throw err;
              this.erweiImg = imgUrl;
            });
          });
        });
        //接收扫码成功的事件
        socket.on("scancodeSuccess", (data) => {
          // console.log(data);
          this.isScancode = true;
          let wechatCode = data.wechatCode;
          //扫码登入请求
          erweiLoginApi(wechatCode).then((res) => {
            // this.$store.dispatch('GET_MENU')
            // console.log(res);
            //将token保存到本地
            localStorage.setItem("qf-token", res.data.token);

            //将个人信息保存到本地
            localStorage.setItem("qf-info", JSON.stringify(res.data.userInfo));
            this.SETUSERINFO(res.data.userInfo);
            //跳转到主页
            this.$router.push("/");
          });
        });
      }
    },
  },
};
</script>

<style scoped lang="less">
#box {
  width: 100%;
  position: relative;
  video {
    min-width: 100%;
    min-height: 100%;
    position: fixed;
    top: 0;
    left: 0;
  }
  .img1 {
    position: absolute;
    top: 250px;
    left: 200px;
    z-index: 8;
    opacity: 0.7;
    height: 300px;
    width: 300px;
  }
  .hh {
    font-size: 30px;
    text-align: center;
    margin-top: 70px;
  }

  #form {
    position: absolute;
    top: 150px;
    right: 200px;
    z-index: 9;
    height: 430px;
    width: 330px;
    color: white;
    background: rgba(0, 0, 0, 0.3);
    box-sizing: border-box;
    border-radius: 10px;
    .iconBox {
      position: absolute;
      right: 3px;
      top: 3px;
      .icon {
        height: 40px;
        width: 40px;
      }
    }
    .erwei {
      text-align: center;
      .imgBox {
        position: relative;
        .img2 {
          display: block;
          height: 180px;
          width: 180px;
          padding: 30px 0 15px 75px;
        }
        .mask {
          height: 180px;
          width: 180px;
          position: absolute;
          top: 30px;
          left: 75px;
          opacity: 0.8;
          background-color: white;
          background-image: url("../../assets/img/扫码成功.png");
          background-repeat: no-repeat;
          background-size: 50%;
          background-position: center;
        }
      }
    }
    .demo-ruleForm {
      position: absolute;
      top: 150px;
      right: 55px;
      color: white;

      & /deep/ .el-form-item__label {
        color: white;
      }
      & /deep/.el-input__inner {
        height: 34px;
        opacity: 0.7;
      }

      .content {
        width: 175px;
        height: 34px;
        margin-bottom: 0;
        display: flex;
        & /deep/.el-input-3 {
          width: 50%;
          border-top-right-radius: 0;
          border-bottom-right-radius: 0;
          .el-input__inner {
            border-top-right-radius: 0;
            border-bottom-right-radius: 0;
            border: none;
          }
        }
        & /deep/.span {
          display: inline-block;
          height: 33.5px;
          width: 50%;
          position: absolute;
          right: 0px;
          top: 4px;
          background: #fff;
          opacity: 0.7;
          border-top-right-radius: 4px;
          border-bottom-right-radius: 4px;
          cursor: pointer;
          svg {
            height: 34px;
            width: 90px;
          }
        }
      }

      .el-button {
        width: 175px;
        height: 34px;
        background: linear-gradient(rgb(4, 37, 223), rgb(107, 188, 243));
      }
    }
  }
}
</style>
